// 导航守卫
import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
// 如果有token登录页面
  if (store.getters.token) {
    // console.log('token', store.getters.token)
    if (to.path === '/login') {
      // 强行跳到首页
      next('/login')
    } else {
      if (Object.keys(store.state.user.userInfo).length === 0) {
        console.log(1)
        // 获取用户信息
        store.state.permission.router = []
        await store.dispatch('user/getUserInfo')
      }
      // 动态路由设置
      if (store.state.permission.router.length === 0) {
        console.log(2)
        const perm = store.state.user.permsList
        const res = await store.dispatch('permission/filterRouter', perm)
        console.log('res', res)
        router.addRoutes([
          ...res,
          { path: '*', redirect: '/404', hidden: true }
        ])
        return next(to.path)
      }
      next()
    }
  } else {
    const whiteList = ['/login', '/404', '/register']
    if (whiteList.indexOf(to.path) !== -1) {
      // 代表存在
      next()
    } else {
      next('/login')
    }
  }
})
